let express = require('express');
let router = express.Router();

const sickenService = require('../service/sickenService');
const checkJWTMiddleWare = require('../middleWare/checkJWTMiddleWare');

// 此路由需要登录后才能访问
router.use(checkJWTMiddleWare);

/*
 * 新增病例档案接口
 */
router.post('/addSickenRecord', async function (req, res, next) {
    let studentId = req.body.studentId;
    let time = req.body.time;
    let hospital = req.body.hospital;
    let sickenTypeId = req.body.sickenTypeId;
    let note = req.body.note;                   // 病情描述
    let photoUrl = req.body.photoUrl;           // 诊断证明 base64 URL

    if (!studentId || !time || !hospital || !sickenTypeId) {
        res.status(400).json({ success: false, msg: "参数不足，新增失败" });
        return ;
    }

    photoUrl = photoUrl || '';

    // 判断 photoUrl这个base64字符串占用的字节是否超过 10M, 超过直接返回失败
    if (Buffer.byteLength(photoUrl, 'utf8') > 10 * 1024 * 1024) {
        res.status(400).json({ success: false, msg: "图片过大，请重新上传" });
        return ;
    }

    let result;
    if (photoUrl) {
        result = await sickenService.addSickenRecord(req.jwtResult.data.uid, studentId, time, hospital, sickenTypeId, note, photoUrl);
    } else {
        result = await sickenService.addSickenRecordNoImg(req.jwtResult.data.uid, studentId, time, hospital, sickenTypeId, note);
    }

    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 获取所有病例类型的接口
 */
router.get('/getAllSickenType', async function (req, res, next) {
    let result = await sickenService.getAllSickenType();
    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 查询某个学生的所有病例档案接口
 */
router.post('/getSickenRecordByStudent', async function (req, res, next) {
    let studentId = req.body.studentId;
    if (!studentId) {
        res.status(400).json({ success: false, msg: "参数不足，查询失败" });
        return ;
    }
    let result = await sickenService.getSickenRecordByStudent(req.jwtResult.data.uid, req.jwtResult.data.userType, studentId);
    res.status(result.success ? 200 : 400).json(result);
});

module.exports = router;
